package com.hzb.LNReader;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.hzb.LNReader.convertor.HtmlParser;
import com.hzb.LNReader.convertor.HtmlToTxtConvertor;
import com.hzb.LNReader.util.ReaderPref;

public class FileSelectActivity extends Activity {
	static final String LOG = FileSelectActivity.class.getSimpleName();
	
	private static final String ICON = "icon";
	private static final String NAME = "name";
	private static final String FILE = "file";
	private final String[] adapterFrom = new String[] {ICON, NAME};
	private final int[] adapterTo = new int[] {R.id.Icon, R.id.FileName};
	
	private File rootDir;
	private File currDir;
	private int rootLen;
	
	private ListView fileView;
	private TextView title;
	private String homeStr;
	
	@Override
	protected void onResume() {
		super.onResume();
		
	}
	
	void openReader(File dstFile) {
		Intent intent = new Intent(FileSelectActivity.this, ReaderActivity.class);
		if (dstFile != null) {
			intent.putExtra(ReaderActivity.DST_FILE, dstFile.getAbsolutePath());
		}
		startActivity(intent);
		finish();
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fileselectlayout);

		homeStr = getString(R.string.fileHome);
		title = (TextView) findViewById(R.id.fileCurrDir);
		fileView = (ListView) findViewById(R.id.fileList);
		
		setRootFile(ReaderPref.getRootDir());
		
		fileView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				HashMap<String, Object> entry = (HashMap<String, Object>) parent.getItemAtPosition(position);
				File file = (File) entry.get(FILE);
				if (file.isDirectory()) {
					updateFileList(file);
				} else {
					File dstFile = getFile(file);
					openReader(dstFile);
				}
			}

			
		});
		fileView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				return false;
			}
		});
			
		updateFileList(rootDir);
	}

	private void setRootFile(String rootPath) {
		rootDir = new File(rootPath);
		if (!rootDir.exists()) {
			rootDir = new File("/sdcard");
		}
		if (!rootDir.exists()) rootDir = new File("/");
		rootLen = rootDir.getPath().length();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = this.getMenuInflater();
		inflater.inflate(R.menu.fileselectmenu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		switch (id) {
		case R.id.showHistory: {
			Intent intent = new Intent(this, ShowHistoryActivity.class);
			startActivity(intent);
			finish();
			break;
		}
		case R.id.setting: {
			Intent intent = new Intent(this, SettingActivity.class);
			startActivity(intent);
			finish();
			break;
		}
		case R.id.exit:
			finish();
			break;
		}
		return true;
	}
	
	private File getFile(File file) {
		String name = file.getName();
		int dotIndex = name.lastIndexOf('.');
		if (dotIndex != -1) {
			dotIndex ++;
			String extendName = name.substring(dotIndex);
			if (extendName.equalsIgnoreCase("htm")
					|| extendName.equalsIgnoreCase("html")) {
				
				name = "." + name + ".lnd";
				File newFile = new File(file.getParent(), name);
				if ((!newFile.isFile()) || newFile.lastModified() < file.lastModified()) {
					try {
						new HtmlParser(new HtmlToTxtConvertor(newFile)).parse(new FileInputStream(file));
					} catch (Exception e) {
						Builder dialog = new AlertDialog.Builder(this);
						dialog.setTitle("错误");
						dialog.setMessage("文件转换出错,请重新选择文件。");
						dialog.setPositiveButton("OK", new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
						dialog.show();
						
						Log.e(LOG, "Error converting html", e);
						return null;
					}
				}
				return newFile;
			}
		}
		return file;
	}
	
	public void setFileAsHome(View view) {
		try {
			currDir = currDir.getCanonicalFile();
			String absPath = currDir.getAbsolutePath();
			ReaderPref.setRootDir(absPath);
			setRootFile(absPath);
			updateFileList(currDir);
		} catch (Exception e) {
			Log.e(LOG, "", e);
		}
	}
	
	@Override
	public void onBackPressed() {
		if (rootDir.equals(currDir)) {
			if (ReaderHistory.head == null) {
				ReaderHistory.save();
				finish();
			} else {
				openReader(null);
			}
		} else {
			updateFileList(currDir.getParentFile());
		}
		
	}
	
	private static FileFilter filter = new ReaderFileFilter();
	
	void updateFileList(File currDir) {
		File[] currFileList;
		String backDirName = null;
		Map<String, Object> entry;
		List<Map<String, Object>> adapterList;
		
		try {
			currFileList = currDir.listFiles(filter);
			if (currFileList == null) {
				return;
			}
			if (currDir.getAbsolutePath().endsWith("..")) {
				backDirName = currDir.getParentFile().getCanonicalFile().getName();
			}
			adapterList = new ArrayList<Map<String,Object>>();
			if (!currDir.getCanonicalPath().equals("/")) {
				entry = new HashMap<String, Object>();
				entry.put(ICON, R.drawable.folder);
				entry.put(NAME, "..");
				String absPath = currDir.getAbsolutePath();
				if (absPath.endsWith("..") || currDir.equals(rootDir)) {
					entry.put(FILE, new File(currDir, ".."));
				} else {
					entry.put(FILE, currDir.getParentFile());
				}
				
				adapterList.add(entry);
			}
		} catch (Exception e) {
			Log.e(LOG, "Error listing dir", e);
			return;
		}
		
		Arrays.sort(currFileList, new Comparator<File>() {
			@Override
			public int compare(File object1, File object2) {
				if (object1.isFile() && object2.isDirectory()) return 1;
				if (object2.isFile() && object1.isDirectory()) return -1;
				if (object1.isDirectory() && object2.isDirectory()) return object1.compareTo(object2);
				return object1.compareTo(object2);
			}
		});
		this.currDir = currDir;
		if (rootLen == 1) {
			title.setText(currDir.getAbsolutePath());
		} else {
			title.setText(homeStr + currDir.getAbsolutePath().substring(rootLen));
		}
		
		for (File file : currFileList) {
			entry = new HashMap<String, Object>();
			String fileName = file.getName();
			if (backDirName != null && fileName.equals(backDirName)) {
				entry.put(FILE, currDir.getParentFile());
			} else {
				entry.put(FILE, file);
			}
			if (file.isDirectory()) {
				entry.put(ICON, R.drawable.folder);
			} else {
				entry.put(ICON, R.drawable.file);
			}
			entry.put(NAME, file.getName());
			adapterList.add(entry);
		}
		SimpleAdapter fileAdapter = new SimpleAdapter(this, adapterList, R.layout.fileitem, adapterFrom, adapterTo);
		fileView.setAdapter(fileAdapter);
		
	}
}

class ReaderFileFilter implements FileFilter {

	@Override
	public boolean accept(File pathname) {
		if (pathname.isDirectory()) return true;
		String name = pathname.getName();
		if (name.startsWith(".")) return false;
		int dotIndex = name.lastIndexOf('.');
		if (dotIndex == -1) return false;
		String extendName = name.substring(dotIndex + 1);
		
		if (extendName.equalsIgnoreCase("txt")) return true;
		if (extendName.equalsIgnoreCase("lnd")) return true;
		if (extendName.equalsIgnoreCase("htm")) return true;
		if (extendName.equalsIgnoreCase("html")) return true;
		return false;
	}
	
}